{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "9c3f9467",
   "metadata": {},
   "source": [
    "# Reranker"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "35f9065d",
   "metadata": {},
   "source": [
    "<div class=\"alert alert-info\">\n",
    "\n",
    "This tutorial is available as an IPython notebook at [Malaya/example/reranker](https://github.com/huseinzol05/Malaya/tree/master/example/reranker).\n",
    "    \n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "be978366",
   "metadata": {},
   "source": [
    "<div class=\"alert alert-info\">\n",
    "\n",
    "This module trained on both standard and local (included social media) language structures, so it is save to use for both.\n",
    "    \n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "3bffd739",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "os.environ['CUDA_VISIBLE_DEVICES'] = ''\n",
    "os.environ['TF_FORCE_GPU_ALLOW_GROWTH'] = 'true'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "d997083d",
   "metadata": {},
   "outputs": [],
   "source": [
    "import logging\n",
    "\n",
    "logging.basicConfig(level=logging.INFO)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "3fc1e6c6",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/husein/.local/lib/python3.8/site-packages/bitsandbytes/cextension.py:34: UserWarning: The installed version of bitsandbytes was compiled without GPU support. 8-bit optimizers, 8-bit multiplication, and GPU quantization are unavailable.\n",
      "  warn(\"The installed version of bitsandbytes was compiled without GPU support. \"\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "/home/husein/.local/lib/python3.8/site-packages/bitsandbytes/libbitsandbytes_cpu.so: undefined symbol: cadam32bit_grad_fp32\n",
      "CPU times: user 3.22 s, sys: 2.61 s, total: 5.84 s\n",
      "Wall time: 2.92 s\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/husein/dev/malaya/malaya/tokenizer.py:214: FutureWarning: Possible nested set at position 3397\n",
      "  self.tok = re.compile(r'({})'.format('|'.join(pipeline)))\n",
      "/home/husein/dev/malaya/malaya/tokenizer.py:214: FutureWarning: Possible nested set at position 3927\n",
      "  self.tok = re.compile(r'({})'.format('|'.join(pipeline)))\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "import malaya"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "15ea6b17",
   "metadata": {},
   "outputs": [],
   "source": [
    "string1 = 'Pemuda mogok lapar desak kerajaan prihatin isu iklim'\n",
    "string2 = 'Perbincangan isu pembalakan perlu babit kerajaan negeri'\n",
    "string3 = 'kerajaan perlu kisah isu iklim, pemuda mogok lapar'\n",
    "string4 = 'Kerajaan dicadang tubuh jawatankuasa khas tangani isu alam sekitar'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "7dc663d6",
   "metadata": {},
   "outputs": [],
   "source": [
    "news1 = 'Tun Dr Mahathir Mohamad mengakui pembubaran Parlimen bagi membolehkan pilihan raya diadakan tidak sesuai dilaksanakan pada masa ini berikutan isu COVID-19'\n",
    "tweet1 = 'DrM sembang pilihan raya tak boleh buat sebab COVID 19'"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f9d05c4c",
   "metadata": {},
   "source": [
    "### List available HuggingFace models"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "742c6446",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'mesolitica/reranker-malaysian-mistral-64M-32k': {'Size (MB)': 95.7,\n",
       "  'Suggested length': 32768},\n",
       " 'mesolitica/reranker-malaysian-mistral-191M-32k': {'Size (MB)': 332,\n",
       "  'Suggested length': 32768},\n",
       " 'mesolitica/reranker-malaysian-mistral-474M-32k': {'Size (MB)': 884,\n",
       "  'Suggested length': 32768}}"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "malaya.reranker.available_huggingface"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "419d30dc",
   "metadata": {},
   "source": [
    "### Load HuggingFace model\n",
    "\n",
    "```python\n",
    "def huggingface(\n",
    "    model: str = 'mesolitica/reranker-malaysian-mistral-64M-32k',\n",
    "    force_check: bool = True,\n",
    "    **kwargs,\n",
    "):\n",
    "    \"\"\"\n",
    "    Load HuggingFace model for reranking task.\n",
    "\n",
    "    Parameters\n",
    "    ----------\n",
    "    model: str, optional (default='mesolitica/reranker-malaysian-mistral-64M-32k')\n",
    "        Check available models at `malaya.reranker.available_huggingface`.\n",
    "    force_check: bool, optional (default=True)\n",
    "        Force check model one of malaya model.\n",
    "        Set to False if you have your own huggingface model.\n",
    "\n",
    "    Returns\n",
    "    -------\n",
    "    result: malaya.torch_model.huggingface.Reranker\n",
    "    \"\"\"\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "5fdd641e",
   "metadata": {},
   "outputs": [],
   "source": [
    "model = malaya.reranker.huggingface()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "96ab9368",
   "metadata": {},
   "source": [
    "#### Sort batch of strings\n",
    "\n",
    "```python\n",
    "def sort(self, left_string: str, right_strings: List[str]):\n",
    "    \"\"\"\n",
    "    Sort the strings.\n",
    "\n",
    "    Parameters\n",
    "    ----------\n",
    "    left_string: str\n",
    "        reference string.\n",
    "    right_strings: List[str]\n",
    "        query strings, list of strings need to sort based on reference string.\n",
    "\n",
    "    Returns\n",
    "    -------\n",
    "    result: np.array\n",
    "    \"\"\"\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "8650cf14",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(6,)"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "v = model.sort(string1, [string1, string2, string3, string4, tweet1, news1])\n",
    "v.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "d02493e5",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([ 6.898162 ,  5.124153 ,  4.9817924,  4.0060225, -8.165119 ,\n",
       "       -1.5455011], dtype=float32)"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "v"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.10"
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
